package ru.usu.gv.gui.behavior;

import ru.usu.gv.core.I18nService;
import ru.usu.gv.gui.actions.LongAction;
import ru.usu.gv.gui.layout.ILayout;
import ru.usu.gv.uicomponents.UIUtilities;

import javax.media.j3d.Behavior;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.WakeupOnElapsedFrames;

import java.util.Enumeration;

/**
 @author: Sergey Pupyrev 
 Apr 2, 2006
 */

public class GraphLayoutBehavior extends Behavior
{
	private WakeupOnElapsedFrames w = new WakeupOnElapsedFrames(0);
	private ILayout layout;

	public GraphLayoutBehavior(BoundingSphere bound)
	{
		setSchedulingBounds(bound);
	}

	public void setLayout(ILayout layout)
	{
		this.layout = layout;
	}

	@Override
	public void initialize()
	{
		wakeupOn(w);
	}

	@Override
	public void processStimulus(Enumeration arg0)
	{
		wakeupOn(w);
		setEnable(false);
		runInNewThread();
	}

	private void runInNewThread()
	{
		new Thread()
		{
			@Override
			public void run()
			{
				System.out.println("Starting layout '" + layout.getClass().getSimpleName() + "'");
				long startTime = System.currentTimeMillis();
				new LongAction(I18nService.get("action.long"))
				{
					@Override
					protected void runAction()
					{
						try
						{
							layout.applyLayout();
						}
						catch (Exception e)
						{
							System.err.println("Error during layout: " + e.getMessage());
							e.printStackTrace();
							return;
						}

						//UIUtilities.scaleGraph();
						//UIUtilities.centralizeGraph();
						UIUtilities.fitGraphIntoWindow();
					}
				}.execute();
				long endTime = System.currentTimeMillis();
				System.out.println("Layout '" + layout.getClass().getSimpleName() + "' finished (" + (endTime - startTime) / 1000.0 + " sec.)");
			}
		}.start();
	}
}
